﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;

namespace SmartMotion.Core
{
    public class FlowsMgr
    {
        #region 单例

        private static readonly Lazy<FlowsMgr> Instance = new Lazy<FlowsMgr>(() => new FlowsMgr());

        private FlowsMgr()
        {
            FlowsPath = Environment.CurrentDirectory + "\\Flows\\";
            if (!Directory.Exists(FlowsPath))
            {
                Directory.CreateDirectory(FlowsPath);
            }
            Flows = new List<Flow>();
        }

        public static FlowsMgr Ins { get; } = Instance.Value;

        #endregion 单例

        #region 属性

        public string FlowsPath { get; set; }

        public List<Flow> Flows { get; set; }

        #endregion 属性

        public void LoadFLows()
        {
            var files = Directory.GetFiles(FlowsPath, "*.flow");
            foreach (var file in files)
            {
                try
                {
                    var flow = Json.LoadExt<Flow>(file);
                    if (flow != null)
                    {
                        Flows.Add(flow);
                    }
                }
                catch (Exception e)
                {
                    UIMessageBox.ShowError($"加载流程时发现有错误的流程{file}\r{e.Message}");
                }
            }

            GlobalVars.Ins.LoadDic(GlobalVars.FlowVars, FlowsPath + "FLowVars.Var");
        }

        public void SaveFlows()
        {
            foreach (var flow in Flows)
            {
                Json.SaveExt<Flow>(FlowsPath + flow.Name + ".flow", flow);
            }
            GlobalVars.Ins.SaveDic(GlobalVars.FlowVars, FlowsPath + "FLowVars.Var");
        }
    }
}